<?php

/**
 * export actions.
 *
 * @package    raidpoints
 * @subpackage export
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class exportActions extends sfActions
{
    /**
     * Executes index action
     *
     * @param sfRequest $request A request object
     */
    public function executeIndex(sfWebRequest $request)
    {

    }

    public function executeBot(sfWebRequest $request)
    {
        //ini_set('memory_limit', '128M');
        $q = Doctrine::getTable("Raid")
                ->getRaidList();
        $raidRes = $q->execute();


        $server = array();
        $myarray = array();

        $highestversion = 0;
        $query = Doctrine::getTable("History")
                ->createQuery("h")
                ->select("dt")
                ->limit(1)
                ->orderBy("dt desc");
        $result = $query->execute();
        if ($result->count() > 0)
            $highestversion = strtotime($result->getFirst()->getDt()." GMT");

        foreach ($raidRes as $raid)
        {
            $masterTime = gmdate("Y-m-d H:i:s", $raid['version']);
            $masterTimeBefore = gmdate("Y-m-d H:i:s", $raid['version'] - (30*24*60*60));

            $raidList[] = $raid->getId();
            $q = Doctrine::getTable("ViewRaidPlayers")
                    ->createQuery()
                    ->where("raidid=?", $raid['id'])
                    ->andWhere("guildedflag=?", 1)
                    ->andWhere("altid=?", 1)
                    ->andWhere("altrank=?", 0);
            $result = $q->execute();
            foreach ($result as $row)
            {
                $raidID = $row['raidid'];
                $playerID = $row['id'];
                $realm = $raid['server'];

                $myarray[$raid['server']]['player'][utf8_decode(($row['name']))] =
                        array(
                        "id" 		=> $row['id'],
                        "fullname" 	=> utf8_decode($row['fullname']),
                        "name" 		=> utf8_decode($row['name']),
                        "class" 	=> $row['pclass'],
                        "gender" 	=> $row['gender'],
                        "rank" 		=> $row['rank'],
                        "race" 		=> $row['race'],
                        "talent" 	=> $row['talentname'],
                );

                $myarray[$raid['server']]["raid"][$row['raid']][(utf8_decode($row['name']))] = array
                        (
                        "points"		=> $row['points'],
                        "lifetime"		=> $row['lifetime'],
                        "recenthistory"	=> array
                        (
                                0 => array
                                (
                                        "actiontime"=> 0,
                                        "datetime" 	=> 0,
                                        "link"		=> 0,
                                        "ty" 		=> "P",
                                        "waitlist" 	=> false,
                                        "value" 	=> $row['lifetime'],
                                        "action" 	=> "Insert",
                                        "itemid" 	=> 0,
                                        "reason" 	=> "Old Points",
                                ),
                        ),
                        "recentactions"	=> array(),
                );

                $recentItems = Doctrine::getTable("ViewHistory")
                        ->createQuery()
                        ->select("dt, ttype, waitlistflag, SUM(value), itemid, reason")
                        ->where("raidid=?", $raidID)
                        ->andWhere("playerid=?", $playerID)
                        ->andWhere("ttype=?", 'I')
                        ->orderBy("dt")
                        ->andWhere("dt >= ?", $masterTimeBefore)
                        ->andWhere("dt <= ?", $masterTime);

//                $oldItems = Doctrine::getTable("ViewHistory")
//                    ->createQuery()
//                    ->select("SUM(value)")
//                    ->where("raidid=?", $raidID)
//                    ->andWhere("playerid=?", $playerID)
//                    ->andWhere("ttype=?", 'I')
//                    ->andWhere("dt < ?", $masterTimeBefore)
//                    ->orderBy("dt");


                $res = $recentItems->execute();
                $i = 1;
                $total = 0;
                foreach ($res as $r)
                {
                    if ($r['id'] > 0)
                    {
                        //print_r($r->toArray());
                        // echo ($r['date']."<br>\n");
                        // echo (strtotime($res->UserTimeStamp($r['date']))."<br>\n");
                        $myarray[$raid['server']]["raid"][$row['raid']][utf8_decode($row['name'])]["recenthistory"][strtotime($r['dt']."GMT")] = array
                                (
                                "actiontime"=> strtotime($r['dt']."GMT"),
                                "datetime" 	=> strtotime($r['dt']."GMT"),
                                "link"		=> 0,
                                "ty" 		=> $r['ttype'],
                                "waitlist" 	=> $r['waitlistflag'],
                                "value" 	=> ($r['SUM'] ? $r['SUM'] : 0),
                                "action" 	=> "Insert",
                                "itemid" 	=> ($r['itemid'] ? $r['itemid'] : 0),
                                "reason" 	=> $r['reason'],
                        );
                        $i++;
                        $total += ($r['SUM'] ? $r['SUM'] : 0);
                    }
                }

//                $res = $oldItems->execute();
//                if ($res->count() > 0)
//                {
//                    $r = $res->getFirst();
                $myarray[$raid['server']]["raid"][$row['raid']][utf8_decode($row['name'])]["recenthistory"][1] = array
                        (
                        "actiontime"=> 1,
                        "datetime" 	=> 1,
                        "link"		=> 0,
                        "ty" 		=> 'I',
                        "waitlist" 	=> 0,
                        "value" 	=> ($row['points'] - $row['lifetime'])-$total,
                        "action" 	=> "Insert",
                        "itemid" 	=> 0,
                        "reason" 	=> "Archived Points",
                );
                //}
            }
//            $lastupdate = $raid['version'];
//            if ($lastupdate > $highestversion)
//                $highestversion = $lastupdate;
            $server[$raid['server']] = $raid['server'];
        }

        // We'll be outputting a LUA file
        $this->getResponse()->setHttpHeader('Content-Type', 'application/lua');
        $this->getResponse()->setHttpHeader('Content-Disposition','attachment; filename="RPBot.lua"');

        function getAssociatedPlayers($p)
        {
            $q = Doctrine::getTable("Player")
                    ->createQuery()
                    ->where("altid=?", $p->getId());
            $r = $q->execute();
            $returnArray = array();
            if ($r->count() > 0)
            {
                foreach ($r as $player)
                {
                    if ($player->getAltid() != 1)
                        array_merge($returnArray, getAssociatedPlayers($player));
                    $returnArray[] = $player->getFullname();
                }
            }
            return $returnArray;
        }

        $user = $this->getUser();
        $username = strtolower($user->getUsername());
        //echo $username;
        $newQuery = Doctrine::getTable("Player")
                ->createQuery()
                ->where("name=?", $username);
        $r = $newQuery->execute();
        if ($r->count() == 1)
        {
            $mainId = $r->getFirst->getId();
            //echo $r->getFirst()->getName().$r->getFirst()->getAltid();
            while ($r->getFirst()->getAltid() != 1)
            {
                $newQuery = Doctrine::getTable("Player")
                        ->createQuery()
                        ->where("id=?", $r->getFirst()->getAltid());
                $r = $newQuery->execute();
            }
            $playerList = array_merge(array($r->getFirst()->getFullname()), getAssociatedPlayers($r->getFirst()));
        }

        $text = "";
        $text .=  "rpDEBUGBotDB = {\n";
        $text .=  "\t[\"profileKeys\"] = {\n";
        foreach ($server as $s => $data)
        {
            $t = " - ".$s;
            foreach ($playerList as $p)
            {
                $text .=  "\t\t[\"".$p.$t."\"] = \"".$p.$t."\",\n";
            }
        }
        //$text .=  "\t\t[\"".$_GET["key"]."\"] = \"".$_GET["key"]."\",\n";
        $text .=  "\t},\n";
        foreach ( $myarray as $realm => $realmdata )
        {
            $text .=  "\t[\"realm\"] = {\n";
            $text .=  "\t\t[\"".$realm."\"] = {\n";
            $text .=  "\t\t\t[\"player\"] = {\n";
            foreach ( $realmdata["player"] as $player => $playerdata )
            {
                $text .=  "\t\t\t\t[\"".utf8_encode($player)."\"] = {\n"
                        ."\t\t\t\t\t[\"id\"] = ".$playerdata['id'].",\n"
                        ."\t\t\t\t\t[\"fullname\"] = \"".utf8_encode($playerdata['fullname'])."\",\n"
                        ."\t\t\t\t\t[\"name\"] = \"".utf8_encode($playerdata['name'])."\",\n"
                        ."\t\t\t\t\t[\"class\"] = \"".$playerdata['class']."\",\n"
                        ."\t\t\t\t\t[\"gender\"] = \"".$playerdata['gender']."\",\n"
                        ."\t\t\t\t\t[\"rank\"] = \"".$playerdata['rank']."\",\n"
                        ."\t\t\t\t\t[\"race\"] = \"".$playerdata['race']."\",\n"
                        ."\t\t\t\t\t[\"race\"] = \"".$playerdata['race']."\",\n"
                        ."\t\t\t\t\t[\"talent\"] = \"".$playerdata['talent']."\",\n";
                $text .=  "\t\t\t\t},\n";
            }
            $text .=  "\t\t\t},\n";
            $text .=  "\t\t\t[\"raid\"] = {\n";
            foreach ( $realmdata["raid"] as $raid => $raiddata )
            {
                $text .=  "\t\t\t\t[\"".$raid."\"] = {\n";
                foreach ( $raiddata as $player => $playerdata )
                {
                    $text .=  "\t\t\t\t\t[\"".utf8_encode($player)."\"] = {\n";
                    $text .=  "\t\t\t\t\t\t[\"points\"] = ".$playerdata['points'].",\n"
                            ."\t\t\t\t\t\t[\"lifetime\"] = ".$playerdata['lifetime'].",\n"
                            ."\t\t\t\t\t\t[\"recenthistory\"] = {\n";
                    foreach ( $playerdata["recenthistory"] as $k => $eventdata )
                    {
                        $text .=  "\t\t\t\t\t\t\t[".$eventdata['datetime']."] = {\n"
                                ."\t\t\t\t\t\t\t\t[\"actiontime\"] = ".$eventdata['actiontime'].",\n"
                                ."\t\t\t\t\t\t\t\t[\"datetime\"] = ".$eventdata['datetime'].",\n"
                                ."\t\t\t\t\t\t\t\t[\"ty\"] = \"".$eventdata['ty']."\",\n"
                                ."\t\t\t\t\t\t\t\t[\"waitlist\"] = \"".$eventdata['waitlist']."\",\n"
                                ."\t\t\t\t\t\t\t\t[\"value\"] = ".$eventdata['value'].",\n"
                                ."\t\t\t\t\t\t\t\t[\"action\"] = \"".$eventdata['action']."\",\n"
                                ."\t\t\t\t\t\t\t\t[\"itemid\"] = ".$eventdata['itemid'].",\n"
                                ."\t\t\t\t\t\t\t\t[\"reason\"] = \"".$eventdata['reason']."\",\n"
                                ."\t\t\t\t\t\t\t\t[\"link\"] = 0,\n"
                                ."\t\t\t\t\t\t\t}, --[]\n";
                    }
                    $text .=  "\t\t\t\t\t\t},\n";
                    $text .=  "\t\t\t\t\t\t[\"recentactions\"] = {\n";
                    $text .=  "\t\t\t\t\t\t},\n";
                    $text .=  "\t\t\t\t\t},\n";
                }
                $text .=  "\t\t\t\t},\n";
            }
            $text .=  "\t\t\t},\n";
            $text .=  "\t\t\t[\"recentloot\"] = {\n";
            $text .=  "\t\t\t},\n";
            $text .=  "\t\t\t[\"version\"] = {\n";
            $text .=  "\t\t\t\t[\"database\"] = ". $highestversion .",\n";
            $text .=  "\t\t\t\t[\"lastaction\"] = ". $highestversion .",\n";
            $text .=  "\t\t\t\t[\"lastloot\"] = ". 0 .",\n";
            $text .=  "\t\t\t},\n";
            $text .=  "\t\t},\n";
        }

        $text .=  "\t},\n";
        $text .=  "}\n";


        return $this->renderText($text);
    }
}
